import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/goods_detail/horizontal_dash.dart';
import 'package:yp/services/api.dart';

class GetCouponBottomSheet extends StatefulWidget {
  final List availableCoupons;
  final List gotCoupons;

  GetCouponBottomSheet(this.availableCoupons, this.gotCoupons);

  @override
  State<StatefulWidget> createState() =>
      _GetCouponBottomSheetState(availableCoupons, gotCoupons);
}

class _GetCouponBottomSheetState extends State<GetCouponBottomSheet> {
  List _availableCoupons;
  List _gotCoupons;
  List _dataList = [];

  _GetCouponBottomSheetState(this._availableCoupons, this._gotCoupons);

  void _initDataList() {
    if (_availableCoupons != null && _availableCoupons.isNotEmpty) {
      for (var coupon in _availableCoupons) {
        coupon['isGot'] = false;
      }
      _dataList.add("可领优惠券");
      _dataList.addAll(_availableCoupons);
    }
    if (_gotCoupons != null && _gotCoupons.isNotEmpty) {
      for (var coupon in _gotCoupons) {
        coupon['isGot'] = true;
      }
      _dataList.add("已领取优惠券（以下是你账户可用优惠券）");
      _dataList.addAll(_gotCoupons);
    }
  }

  @override
  void initState() {
    super.initState();
    _initDataList();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: const Radius.circular(10),
          topRight: const Radius.circular(10),
        ),
      ),
      child: Stack(
        children: [
          Padding(
              padding: EdgeInsets.only(top: 42),
              child: ListView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 10),
                  itemCount: _dataList.length,
                  itemBuilder: (context, index) {
                    var data = _dataList[index];
                    if (data is String) {
                      return _titleItem(data);
                    } else if (isCashCoupon(data)) {
                      return _cashCouponItem(data);
                    } else if (isDiscountCoupon(data)) {
                      return _discountCouponItem(data);
                    } else if (isFreePostCoupon(data)) {
                      return _freePostCouponItem(data);
                    } else {
                      return Container();
                    }
                  })),
          Row(
            children: [
              Expanded(
                  child: Padding(
                      padding: EdgeInsets.only(
                        left: 15,
                        top: 15,
                      ),
                      child: Text( 
                        '领取优惠券',
                        style: TextStyle(
                          fontSize: 18,
                          color: const Color(0xFF222222),
                          fontWeight: FontWeight.w500,
                        ),
                      ))),
              GestureDetector(
                onTap: () => Navigator.pop(context),
                child: Padding(
                  padding: const EdgeInsets.only(top: 10, right: 10),
                  child: Image.asset(
                    'assets/images/close2.png',
                    width: 20,
                    height: 20,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _titleItem(String title) {
    return Container(
      padding: const EdgeInsets.all(15),
      child: Text(
        title,
        style: TextStyle(
          fontSize: 14,
          color: const Color(0xFF686868),
        ),
      ),
    );
  }

  bool isCashCoupon(var coupon) {
    return (coupon['type_id'] != null && coupon['type_id'] == 1) ||
        (coupon['qtype'] != null && coupon['qtype'] == "1");
  }

  bool isDiscountCoupon(var coupon) {
    return (coupon['type_id'] != null && coupon['type_id'] == 2) ||
        (coupon['qtype'] != null && coupon['qtype'] == "2");
  }

  bool isFreePostCoupon(var coupon) {
    return (coupon['type_id'] != null && coupon['type_id'] == 3) ||
        (coupon['qtype'] != null && coupon['qtype'] == "3");
  }

  String _createCouponUseLimitContent(var coupon) {
    return coupon['least_cost'] != null && coupon['least_cost'] > 0
        ? '满${coupon['least_cost']}元可用'
        : '无门槛';
  }

  String _createCouponDateRange(var coupon) {
    if (coupon['starttime'] != null && coupon['endtime'] != null) {
      return '${DateFormat('yyyy.MM.dd').format(DateTime.parse(coupon['starttime']))}'
          ' - ${DateFormat('yyyy.MM.dd').format(DateTime.parse(coupon['endtime']))}';
    }
    if (coupon['sdate'] != null && coupon['edate'] != null) {
      return '${DateFormat('yyyy.MM.dd').format(DateTime.parse(coupon['sdate']))}'
          ' - ${DateFormat('yyyy.MM.dd').format(DateTime.parse(coupon['edate']))}';
    }
    return '';
  }

  bool _isCouponGot(var coupon) {
    return coupon['isGot'] != null && coupon['isGot'];
  }

  double _getCouponHeight() {
    return 120.0;
  }

  double _getCouponPriceModuleWidth() {
    return MediaQuery.of(context).size.width * 3.2 / 10.0;
  }

  double _getPriceLetterSpacing() {
    return -2.5;
  }

  Widget _cashCouponItem(var coupon) {
    String amount = '';
    if (coupon['face_value'] != null) {
      amount = coupon['face_value'].toString();
    } else if (coupon['qmz'] != null) {
      amount = coupon['qmz'].toString();
    }
    String limit = _createCouponUseLimitContent(coupon);
    String couponType = "现金券";
    String couponDesc = '';
    if (coupon['title'] != null) {
      couponDesc = coupon['title'].toString();
    } else if (coupon['qname'] != null) {
      couponDesc = coupon['qname'].toString();
    }
    const Color _textGreen = const Color(0xFF2C673D);
    return Container(
      height: _getCouponHeight(),
      margin: const EdgeInsets.only(bottom: 20),
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage('assets/images/couponbg_image.png')),
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ),
      child: Row(
        children: [
          Container(
            width: _getCouponPriceModuleWidth(),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 12, top: 30, right: 5),
                  child: RichText(
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    text: TextSpan(
                      children: [
                        TextSpan(
                            text: '¥  ',
                            style: TextStyle(fontSize: 14, color: _textGreen)),
                        TextSpan(
                            text: amount,
                            style: TextStyle(
                              fontSize: 26,
                              color: _textGreen,
                              fontWeight: FontWeight.w500,
                              letterSpacing: _getPriceLetterSpacing(),
                            )),
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: Text(limit,
                      style: TextStyle(fontSize: 14, color: _textGreen)),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              margin: const EdgeInsets.only(left: 5, right: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 20),
                    child: Row(
                      children: [
                        Container(
                            height: 20,
                            padding: const EdgeInsets.symmetric(horizontal: 5),
                            decoration: BoxDecoration(
                              color: _textGreen,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12)),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              couponType,
                              style:
                                  TextStyle(color: Colors.white, fontSize: 10),
                            )),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.only(left: 2),
                            child: Text(
                              couponDesc,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(fontSize: 14),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 15, bottom: 10),
                    child: HorizontalDash(
                      color: Colors.grey,
                    ),
                  ),
                  Text(
                    _createCouponDateRange(coupon),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 15, color: Colors.grey),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: !_isCouponGot(coupon),
            child: GestureDetector(
              onTap: () => getCoupon(coupon),
              child: Container(
                  height: 23,
                  margin: const EdgeInsets.only(right: 5),
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        const Color(0xFF4CA766),
                        const Color(0xFF2B683D)
                      ],
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(13)),
                  ),
                  child: Text(
                    "领取",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                  )),
            ),
          ),
        ],
      ),
    );
  }

  Widget _freePostCouponItem(var coupon) {
    String couponName = "免邮券";
    String couponType = "免邮券";
    String limit = _createCouponUseLimitContent(coupon);
    String couponDesc = '';
    if (coupon['title'] != null) {
      couponDesc = coupon['title'].toString();
    } else if (coupon['qname'] != null) {
      couponDesc = coupon['qname'].toString();
    }
    const Color _textYellow = const Color(0xFFECAB3E);
    return Container(
      height: _getCouponHeight(),
      margin: const EdgeInsets.only(bottom: 20),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/coupon_yellow.png'),
          fit: BoxFit.fill,
        ),
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ),
      child: Row(
        children: [
          Container(
            width: _getCouponPriceModuleWidth(),
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 10, top: 30, right: 10),
                  child: Text(
                    couponName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 26,
                      color: _textYellow,
                      fontWeight: FontWeight.w500,
                      letterSpacing: -1,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: Text(limit,
                      style: TextStyle(fontSize: 14, color: _textYellow)),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              margin: const EdgeInsets.only(left: 5, right: 15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 20),
                    child: Row(
                      children: [
                        Container(
                            height: 24,
                            padding: const EdgeInsets.symmetric(horizontal: 7),
                            decoration: BoxDecoration(
                              color: _textYellow,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12)),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              couponType,
                              style:
                                  TextStyle(color: Colors.white, fontSize: 12),
                            )),
                        Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Text(
                            couponDesc,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontSize: 18),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 15, bottom: 10),
                    child: HorizontalDash(
                      color: Colors.grey,
                    ),
                  ),
                  Text(
                    _createCouponDateRange(coupon),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 15, color: Colors.grey),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: !_isCouponGot(coupon),
            child: GestureDetector(
              onTap: () => getCoupon(coupon),
              child: Container(
                  height: 26,
                  margin: const EdgeInsets.only(right: 15),
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        const Color(0xFF4CA766),
                        const Color(0xFF2B683D)
                      ],
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(13)),
                  ),
                  child: Text(
                    "领取",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  )),
            ),
          ),
        ],
      ),
    );
  }

  Widget _discountCouponItem(var coupon) {
    String discount = '';
    if (coupon['face_value'] != null) {
      discount = (coupon['face_value'] / 10).toString();
    } else if (coupon['qmz'] != null) {
      discount = (coupon['qmz'] / 10).toString();
    }
    String limit = _createCouponUseLimitContent(coupon);
    String couponType = "抵扣券";
    String couponDesc = '';
    if (coupon['title'] != null) {
      couponDesc = coupon['title'].toString();
    } else if (coupon['qname'] != null) {
      couponDesc = coupon['qname'].toString();
    }
    const Color _textYellow = const Color(0xFFECAB3E);
    return Container(
      height: _getCouponHeight(),
      margin: const EdgeInsets.only(bottom: 20),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/coupon_yellow.png'),
          fit: BoxFit.fill,
        ),
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ),
      child: Row(
        children: [
          Container(
            width: _getCouponPriceModuleWidth(),
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 10, top: 28, right: 10),
                  child: RichText(
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    text: TextSpan(
                      children: [
                        TextSpan(
                            text: discount,
                            style: TextStyle(
                                fontSize: 30,
                                color: _textYellow,
                                fontWeight: FontWeight.w500)),
                        TextSpan(
                            text: '折',
                            style: TextStyle(fontSize: 14, color: _textYellow)),
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: Text(limit,
                      style: TextStyle(fontSize: 14, color: _textYellow)),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              margin: const EdgeInsets.only(left: 5, right: 15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 20),
                    child: Row(
                      children: [
                        Container(
                            height: 26,
                            padding: const EdgeInsets.symmetric(horizontal: 7),
                            decoration: BoxDecoration(
                              color: _textYellow,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(13)),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              couponType,
                              style:
                                  TextStyle(color: Colors.white, fontSize: 12),
                            )),
                        Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Text(
                            couponDesc,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontSize: 18),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 15, bottom: 10),
                    child: HorizontalDash(
                      color: Colors.grey,
                    ),
                  ),
                  Text(
                    _createCouponDateRange(coupon),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 15, color: Colors.grey),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: !_isCouponGot(coupon),
            child: GestureDetector(
              onTap: () => getCoupon(coupon),
              child: Container(
                  height: 26,
                  margin: const EdgeInsets.only(right: 15),
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        const Color(0xFF4CA766),
                        const Color(0xFF2B683D)
                      ],
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(13)),
                  ),
                  child: Text(
                    "领取",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  )),
            ),
          ),
        ],
      ),
    );
  }

  void getCoupon(var coupon) {
    void _updateDataList(var coupon) {
      if (_availableCoupons != null) {
        _availableCoupons.remove(coupon);
      }
      if (_gotCoupons == null) {
        _gotCoupons = [];
      }
      _gotCoupons.add(coupon);
    }

    String couponNumId = coupon['series'].toString();
    var params = {
      "use_platform": 2,
      "coupon_num_id": couponNumId, //券编码
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "access_token": SpUtil.getString('token'),
      "relation": "领券中心",
      "qsource": 301,
      "relation_indate": "永久有效",
      "user_num_id": SpUtil.getInt('empeNumId'),
    };
    Api.getCoupon(params).listen((event) {
      if (event['code'] == 0) {
        toast('领券成功');
        coupon['isGot'] = true;
        _updateDataList(coupon);
        _dataList.clear();
        _initDataList();
        setState(() {});
      } else {
        toast(event['message']);
      }
    });
  }
}
